package com.xiaoniu.forum.common.ali;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.xiaoniu.forum.common.utils.IdGen;
import com.xiaoniu.forum.renren.common.utils.RedisUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 短信验证码生成工具
 */
@Slf4j
public class AliSMSCodeUtil {

    public static boolean getSMSCode(String phone, Map<String,Object> param) throws ClientException {
        if(StringUtils.isEmpty(phone)) return false;
        log.info("准备为手机号{{}}发送验证码",phone);
        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI4G3HZJGbXHmtnzqpsj4m", "VIBdYDIYy8rXLc3qz1Cs0HmfUsog2u");
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定的参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",phone); //手机号
        request.putQueryParameter("SignName","小牛谷粒学院在线教育网站"); //申请阿里云 签名名称
        request.putQueryParameter("TemplateCode","SMS_195586655"); //申请阿里云 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //验证码数据，转换json数据传递

        try {
//            最终发送
            CommonResponse response = client.getCommonResponse(request);
            log.info("验证码返回结果为:{{}}",response.getData());
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        }catch(Exception e) {
            log.error("发送验证码失败");
            e.printStackTrace();
            return false;
        }

    }

    @Data
    public static class SmsResponse {
        //状态 "OK"成功
        String code;
        //验证码
        String number;
    }

    public static void main(String[] args) throws ClientException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",IdGen.getRandom4Num());
        map.put("code",IdGen.getRandom4Num());

        boolean smsCode = AliSMSCodeUtil.getSMSCode("15728727008", map);
        System.out.println(smsCode);
    }
}
